/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.tamnhat.lazyLoading;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.primefaces.model.LazyDataModel;
import org.primefaces.model.SortOrder;

/**
 *
 * @author Administrator
 */
public class LazyAbstractDataModel<T> extends LazyDataModel<T> {        
    private List<T> datasource = new ArrayList<T>();

    public LazyAbstractDataModel(List<T> datasource) {
        this.datasource = datasource;
    }
    
    @Override
    public T getRowData(String rowKey) {
        return null;
    }
    
    @Override
    public Object getRowKey(T s) {
        return null;
    }
    
    @Override
    public List<T> load(int first, int pageSize, String sortField, SortOrder sortOrder, Map<String, String> filters) {
        List<T> data = new ArrayList<T>();
        List<T> test = new ArrayList<T>();
            //filter
            for (T s : datasource) {
                boolean match = true;
                
                for (Iterator<String> it = filters.keySet().iterator(); it.hasNext();) {
                    try {
                        String filterProperty = it.next();
                        String filterValue = filters.get(filterProperty);
                        String fieldValue = String.valueOf(s.getClass().getField(filterProperty).get(s));
                        
                        if (filterValue == null || fieldValue.startsWith(filterValue)) {
                            match = true;
                        } else {
                            match = false;
                            break;
                        }
                    } catch (Exception e) {
                        match = false;
                        e.printStackTrace();
                    }
                }
                
                if (match) {
                    data.add(s);
                }
                
            }
            //sort  
            if (sortField != null) {
//            Collections.sort(data, new LazySorter(sortField, sortOrder));
            }

            //rowCount  
            int dataSize = data.size();
            this.setRowCount(dataSize);

            //paginate  
            if (dataSize > pageSize) {
                try {
                    test = data.subList(first, first + pageSize);                    
                    return data.subList(first, first + pageSize);
                } catch (IndexOutOfBoundsException e) {
                    test = data.subList(first, first + (dataSize % pageSize));
                    return data.subList(first, first + (dataSize % pageSize));
                }
            } else {
                return data;
            }        
    }
    
}
